<script setup lang="ts">
import { ref, getCurrentInstance, computed, onMounted,onUnmounted, watch } from 'vue'
import { storeToRefs } from 'pinia';
import { adminStore } from '../../store/admin'
import { userStore } from '../../store/user'
import { gatewayStore } from '../../store/gateway'
import indexDb from '../../local/indexDb'
import { channelNameDb } from '../../local/channelNameDb'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Warning, Refresh, Delete, Close, Search } from '@element-plus/icons-vue'
import { alarmStore } from '../../store/alarm'
const alarm_store = alarmStore()
const { alarmConfig } = storeToRefs(alarm_store)

const admin_store = adminStore()
const user_store = userStore()
const gateway_store = gatewayStore()
const { isOpenDrawer } = storeToRefs(admin_store)
const { indexDbNum } = storeToRefs(user_store)
const { gatewayList } = storeToRefs(gateway_store)
const { proxy }: any = getCurrentInstance()

// 数据状态
const errList = ref<any[]>([])
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const totalRecords = ref<number>(0)

// 设备名称映射
const deviceNameMap = ref<Map<string, string>>(new Map())

// 筛选状态
const filterGatewayName = ref<string>('')
const filterGatewayIp = ref<string>('')
const filterSensorType = ref<string>('')
const filterDeviceName = ref<string>('')

// 计算过滤后的数据
const filteredErrList = computed(() => {
  let filtered = errList.value
  
  if (filterGatewayName.value) {
    filtered = filtered.filter(item => item.gatewayName === filterGatewayName.value)
  }
  
  if (filterGatewayIp.value) {
    filtered = filtered.filter(item => item.gatewayIp === filterGatewayIp.value)
  }
  
  if (filterSensorType.value) {
    filtered = filtered.filter(item => item.sensorType === filterSensorType.value)
  }
  
  if (filterDeviceName.value) {
    filtered = filtered.filter(item => {
      const deviceName = getDeviceName(item.gatewayIp, item.deviceId)
      return deviceName.includes(filterDeviceName.value)
    })
  }
  
  return filtered
})

// 获取设备名称
const getDeviceName = (gatewayIp: string, deviceId: string) => {
  const key = `${gatewayIp}-${deviceId}`
  return deviceNameMap.value.get(key) || `监测点 ${deviceId}`
}

// 获取传感器图标
const getSensorIcon = (sensorType: string) => {
  const icons = {
    '温度': '🌡️',
    '湿度': '💧',
    '压力': '📊',
    '红外': '🔴',
    '紫外': '☀️'
  }
  return icons[sensorType as keyof typeof icons] || '📡'
}

// 获取传感器标签类型
const getSensorTagType = (sensorType: string) => {
  const types = {
    '温度': 'danger',
    '湿度': 'primary',
    '压力': 'warning',
    '红外': 'danger',
    '紫外': 'warning'
  }
  return types[sensorType as keyof typeof types] || 'info'
}

// 获取行样式
const getRowClassName = ({ row }: { row: any }) => {
  if (row.level === 'error') {
    return 'error-row'
  } else if (row.level === 'success') {
    return 'success-row'
  }
  return ''
}

// 表头样式
const headerStyle = () => {
  return {
    'text-align': 'center',
    'background-color': '#f5f7fa',
    'color': '#606266',
    'font-weight': 'bold'
  }
}

// 关闭抽屉
const handleClose = async () => {
  isOpenDrawer.value = false
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  renderErrorList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  renderErrorList()
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  renderErrorList()
}

// 渲染错误列表
const renderErrorList = async () => {
  try {
    const result = await indexDb.getAllData() as any[]
    console.log('从 IndexedDB 读取的原始报警数据:', JSON.parse(JSON.stringify(result)));
    totalRecords.value = result.length
    
    // 按时间戳降序排序
    result.sort((a, b) => new Date(b.timestamp || b.date).getTime() - new Date(a.timestamp || a.date).getTime())
    
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    errList.value = result.slice(startIndex, endIndex)
  } catch (error) {
    console.error('获取报警列表失败:', error)
    ElMessage.error('获取报警列表失败')
  }
}

// 刷新列表
const refreshList = async () => {
  await renderErrorList()
  const count = await indexDb.countNum()
  indexDbNum.value = count
  ElMessage.success('列表已刷新')
}

// 删除单条记录
const deleteRecord = async (id: number) => {
  console.log('准备删除的记录 ID:', id); // 添加日志记录ID
  try {
    await ElMessageBox.confirm(
      '确定要删除这条报警记录吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await indexDb.deleteById(id)
    await renderErrorList()
    const count = await indexDb.countNum()
    indexDbNum.value = count
    ElMessage.success('记录已删除')
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除记录失败:', error);
      ElMessage.error('删除记录失败，请查看控制台获取更多信息。');
    }
  }
}

// 清空所有信息
const closeInfo = async () => {
  try {
    const res = await ElMessageBox.confirm(
      "确定要清空所有报警信息吗？此操作不可恢复！",
      "清空确认",
      {
        confirmButtonText: "确定清空",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true
      }
    )
    
    if (res === "confirm") {
      await indexDb.deleteData()
      isOpenDrawer.value = false
      indexDbNum.value = 0
      errList.value = []
      ElMessage.success('所有报警信息已清空')
      // 新增：清空报警时，立即停止语音报警和清除所有活跃报警
      if (window.speechSynthesis) {
        window.speechSynthesis.cancel();
      }
      // 通知主页面的 alarmWorker 清除所有报警
      if ((window as any).__alarmWorker) {
        (window as any).__alarmWorker.postMessage({ type: 'clear_all_alarms' });
      } else if (window.parent && (window.parent as any).__alarmWorker) {
        (window.parent as any).__alarmWorker.postMessage({ type: 'clear_all_alarms' });
      }
    }
  } catch {
    // 用户取消操作
  }
  // 新增：关闭时也停止语音报警和清除所有活跃报警
  if (window.speechSynthesis) {
    window.speechSynthesis.cancel();
  }
  if ((window as any).__alarmWorker) {
    (window as any).__alarmWorker.postMessage({ type: 'clear_all_alarms' });
  } else if (window.parent && (window.parent as any).__alarmWorker) {
    (window.parent as any).__alarmWorker.postMessage({ type: 'clear_all_alarms' });
  }
}

// 新增：报警开关切换
const toggleAlarmEnabled = () => {
  alarm_store.alarmConfig.enabled = !alarm_store.alarmConfig.enabled;
  // 通知 alarmWorker 更新配置
  if ((window as any).__alarmWorker) {
    (window as any).__alarmWorker.postMessage({
      type: 'update_config',
      data: { enabled: alarm_store.alarmConfig.enabled }
    });
  }
  ElMessage({
    message: alarm_store.alarmConfig.enabled ? '报警已开启' : '报警已关闭',
    type: alarm_store.alarmConfig.enabled ? 'success' : 'info',
    duration: 2000
  });
}


watch(indexDbNum,() => {
  renderErrorList()
})
// 加载设备名称映射
const loadDeviceNames = async () => {
  try {
    const nameMap = await channelNameDb.getAllNames()
    deviceNameMap.value = nameMap
  } catch (error) {
    console.error('加载设备名称失败:', error)
  }
}
const handler = async (): Promise<void> => {
     // 加载设备名称映射
    await loadDeviceNames()
}

// 初始化
onMounted(async () => {
  try {
    await indexDb.openDb("list")
    const count = await indexDb.countNum()
    indexDbNum.value = count
    
    // 加载设备名称映射
    await loadDeviceNames()
    
    await renderErrorList()

    window.addEventListener('update_device_names', handler as EventListener)
  } catch (error) {
    console.error('初始化报警列表失败:', error)
  }
})

onUnmounted(() => {
  window.removeEventListener('update_device_names', handler as EventListener)
})


</script>
<template>
  <!-- 抽屉 -->
  <el-drawer 
    v-model="isOpenDrawer"
    direction="btt"
    :before-close="handleClose"
    :show-close="false"
    size="50%"
    class="alarm-drawer"
  >
    <template #header>
      <div class="drawer-header">
        <div class="header-title">
          <el-icon class="alarm-icon"><Warning /></el-icon>
          <h3>报警信息列表</h3>
          <el-tag type="danger" size="small">{{ indexDbNum }}条</el-tag>
        </div>
        <div class="header-actions">
          <el-button type="primary" size="small" @click="refreshList">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button type="danger" size="small" @click="closeInfo">
            <el-icon><Delete /></el-icon>
            清空所有
          </el-button>
          <el-button type="info" size="small" @click="isOpenDrawer = false">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
          <!-- 新增：报警开关按钮 -->
          <el-button :type="alarmConfig.enabled ? 'success' : 'warning'" size="small" @click="toggleAlarmEnabled" style="margin-left: 10px;">
            <el-icon v-if="alarmConfig.enabled" style="color: #52c41a; font-size: 18px;"><i class="el-icon el-icon-bell"></i></el-icon>
            <el-icon v-else style="color: #f56c6c; font-size: 18px;"><i class="el-icon el-icon-bell"></i></el-icon>
            {{ alarmConfig.enabled ? '报警开启' : '报警关闭' }}
          </el-button>
        </div>
      </div>
    </template>
    
    <template #default>
      <div class="alarm-content">
        <!-- 筛选器 -->
        <div class="filter-section">
          <el-row :gutter="16">
            <el-col :span="6">
              <el-select v-model="filterGatewayName" placeholder="网关名称" size="small" @change="handleFilter">
                <el-option label="全部" value=""></el-option>
                <el-option 
                  v-for="gateway in gatewayList" 
                  :key="gateway.id" 
                  :label="gateway.name" 
                  :value="gateway.name"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="filterSensorType" placeholder="传感器类型" size="small" @change="handleFilter">
                <el-option label="全部" value=""></el-option>
                <el-option label="温度" value="温度"></el-option>
                <el-option label="湿度" value="湿度"></el-option>
                <el-option label="压力" value="压力"></el-option>
                <el-option label="红外" value="红外"></el-option>
                <el-option label="紫外" value="紫外"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-input v-model="filterDeviceName" placeholder="设备名称" size="small" @input="handleFilter">
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
          </el-row>
        </div>

        <!-- 报警列表 -->
        <div class="alarm-list">
          <el-table
            :data="filteredErrList"
            :default-sort="{ prop: 'timestamp', order: 'descending' }"
            style="width: 100%;"
            :header-cell-style="headerStyle"
            :row-class-name="getRowClassName"
            stripe
            border
            height="500"
          >
            <el-table-column type="index" label="#" width="50" align="center"></el-table-column>
            
            <el-table-column prop="gatewayName" label="网关名称" width="120" align="center">
              <template #default="scope">
                <el-tag type="primary" size="small">{{ scope.row.gatewayName || '未知' }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="gatewayIp" label="网关IP" width="120" align="center">
              <template #default="scope">
                <el-tag type="info" size="small">{{ scope.row.gatewayIp }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="deviceId" label="设备" width="120" align="center">
              <template #default="scope">
                <el-tag type="warning" size="small">{{ getDeviceName(scope.row.gatewayIp, scope.row.deviceId) }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="sensorType" label="传感器" width="100" align="center">
              <template #default="scope">
                <el-tag 
                  :type="getSensorTagType(scope.row.sensorType)"
                  size="small"
                >
                  {{ getSensorIcon(scope.row.sensorType) }} {{ scope.row.sensorType }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="actualValue" label="实际数值" width="100" align="center">
              <template #default="scope">
                <span class="actual-value">
                  {{ scope.row.actualValue !== undefined ? scope.row.actualValue : '-' }}
                </span>
              </template>
            </el-table-column>
            
            <el-table-column prop="date" label="时间" width="150" align="center" sortable></el-table-column>
            
            <el-table-column prop="info" label="详细信息" min-width="200">
              <template #default="scope">
                <div class="message-content">
                  <!-- <el-tooltip :content="scope.row.info" placement="top"> -->
                    <span>{{ scope.row.info }}</span>
                  <!-- </el-tooltip> -->
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteRecord(scope.row.id)"
                  :icon="Delete"
                  circle
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="totalRecords"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped lang="less">
.alarm-drawer {
  .drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    border-bottom: 1px solid #ebeef5;
    
    .header-title {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .alarm-icon {
        color: #f56c6c;
        font-size: 24px;
      }
      
      h3 {
        margin: 0;
        color: #303133;
      }
    }
    
    .header-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.alarm-content {
  padding: 20px;
  display: flex;
  flex-direction: column;
  
  .filter-section {
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 6px;
    flex-shrink: 0; /* 防止过滤器被压缩 */
  }
  
  .alarm-list {
    flex: 1; /* 占据剩余空间 */
    margin-bottom: 20px;
    overflow: hidden; /* 防止溢出 */
    
    .error-value {
      color: #f56c6c;
      font-weight: bold;
    }
    
    .normal-value {
      color: #67c23a;
    }
    
    /* 为表格容器添加滚动 */
    :deep(.el-table) {
      height: 100% !important;
    }
    
    :deep(.el-table__body-wrapper) {
      max-height: calc(100vh - 400px) !important; /* 动态计算表格主体最大高度 */
      overflow-y: auto !important;
    }
  }
  
  .pagination-section {
    display: flex;
    justify-content: center;
    padding: 20px 0;
    flex-shrink: 0; /* 确保分页器始终可见 */
    border-top: 1px solid #ebeef5; /* 添加顶部边框分隔 */
    background: #fafafa; /* 添加背景色突出显示 */
  }
}

// 表格行样式
:deep(.error-row) {
  background-color: #fef0f0 !important;
}

:deep(.success-row) {
  background-color: #f0f9ff !important;
}

:deep(.el-table__row:hover) {
  background-color: #ecf5ff !important;
}
</style>